﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DownloadBook.Entity {
    public class ProxyConfig {
        /// <summary>
        /// 是否启用代理
        /// </summary>
        public bool Enabled { get; set; } = false;

        /// <summary>
        /// 代理类型
        /// </summary>
        public ProxyType ProxyType { get; set; } = ProxyType.Http;

        /// <summary>
        /// 主机名称
        /// </summary>
        public string HostName { get; set; }

        /// <summary>
        /// 端口
        /// </summary>
        public int Port { get; set; } = 8080;

        /// <summary>
        /// 是否需要身份验证
        /// </summary>
        public bool NeedAuthentication { get; set; }

        /// <summary>
        /// 用户名
        /// </summary>
        public string UserName { get; set; }

        /// <summary>
        /// 密码
        /// </summary>
        public string Passwrod { get; set; }

        /// <summary>
        /// 获取配置文件路径
        /// </summary>
        /// <returns></returns>
        private static string GetConfigFilePath() {
            return Path.Combine(Environment.CurrentDirectory, "ProxyConfig.json");
        }

        /// <summary>
        /// 从文件中载入配置
        /// </summary>
        /// <returns></returns>
        public static ProxyConfig LoadFromFile() {
            ProxyConfig proxyConfig = null;
            string filePath = GetConfigFilePath();
            if (File.Exists(filePath)) {
                string json = File.ReadAllText(filePath);
                proxyConfig = JsonConvert.DeserializeObject<ProxyConfig>(json);
            }
            if(proxyConfig == null) {
                proxyConfig = new ProxyConfig();
            }
            return proxyConfig;
        }

        /// <summary>
        /// 保存信息到文件
        /// </summary>
        /// <param name="proxyConfig"></param>
        public static void SaveToFile(ProxyConfig proxyConfig) {
            string filePath = GetConfigFilePath();
            string json = JsonConvert.SerializeObject(proxyConfig, Formatting.Indented);
            File.WriteAllText(filePath, json);
        }
    }
}
